# -*- coding: UTF-8 -*- 
import time,random,re,logging,os,getpass,sys,urllib2,urllib
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
import PyQt4.QtNetwork
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
from urlparse import urlparse
import datetime,cookielib
from StringIO import StringIO
import gzip,json
import DarenImage

reload(sys)
sys.setdefaultencoding('UTF-8')

#等待睡眠
def timeSleep():
	time.sleep(2)

#时间戳
def datetime2timestamp(dt, convert_to_utc=False):
    ''' Converts a datetime object to UNIX timestamp in milliseconds. '''
    if isinstance(dt, datetime.datetime):
        if convert_to_utc: # 是否转化为UTC时间
            dt = dt + datetime.timedelta(hours=-8) # 中国默认时区
        timestamp = total_seconds(dt - EPOCH)
        return long(timestamp)
    return dt

def timestamp_now():
	return str( int(time.time()) * 100 )

def redaTxt(fileName):
	if os.path.exists(fileName):
	    f = open(fileName, 'r')
	    return f.read()
	else:
	    f = open(fileName,'w')
	    return ""

def mkdir(path):
    path=path.strip()
    path=path.rstrip("\\")
    isExists=os.path.exists(path)
    if not isExists:
        os.makedirs(path)
        return True
    else:
        return False

def saveTxt(fileName,body):
	f = open(fileName,'wb')
	f.write(str(body))
	f.close()

def outTxt(v):
	return str(v)

def Login():
	print u"检查到需要手动登陆"
	options = webdriver.ChromeOptions()
	chromedriver = str(os.getcwdu()) + "\chromedriver.exe"
	os.environ["webdriver.chrome.driver"] = chromedriver
	driver = webdriver.Chrome(chrome_options=options,executable_path=chromedriver) # Get local session of firefox
	driver.set_page_load_timeout(100)
	driver.set_window_size(1200, 900)
	url = "https://login.taobao.com/member/login.jhtml?redirectURL=http%3A%2F%2Fwe.taobao.com%2Fdaren%2Findex.htm"
	driver.get(url)

    #检测URL是否已经变化，变化我就认为登录成功，简单点嘛
	while True:
		if driver.current_url == "http://we.taobao.com/daren/index.htm":
			break
		time.sleep(3)
	page_source = driver.page_source.encode('utf-8')

	input =re.findall('<input .*? name=\"_tb_token_\".*? value=\"(.*?)\"',page_source)
	tb_token = input[0]

	cookies = ""
	#遍历cookies中的name 和value信息打印，当然还有上面添加的信息
	for cookie in driver.get_cookies():
	    cookies += "%s=%s; " % (cookie['name'], cookie['value'])

	saveTxt("cache_tb_token.txt",tb_token)  #保存tb_token
	saveTxt("cache_cookies.txt",cookies)    #保存cookies
	driver.quit()

#单品规则
def SingleProduct(dataJson):

	tb_token = redaTxt("cache_tb_token.txt")
	cookies  = redaTxt("cache_cookies.txt")
	if dataJson == "":
		data     = redaTxt("cache_data.txt")
	else:
		data = urllib.unquote(dataJson)
	timestamp = timestamp_now()
	url       = "http://we.taobao.com/action.do?api=primus_msg_do_publish_feed&subApi=publish_item&_input_charset=utf-8&_tb_token_="+tb_token+"&timestamp=" + timestamp
	data      = re.sub('"_tb_token_":"(.*)"', '"_tb_token_":"'+str(tb_token)+'"',data) #正则替换token
	coverUrl  = re.findall(r'coverUrl":"(.*)","nodes"',data,re.S) #正则提取coverUrl

	r1 = re.compile('"id":"(.+?)"')
	id = re.findall(r1, data)[0]
	data = data.replace('"id":"'+str(id)+'",',"")

	try:
		DarenCoverUrl = DarenImage.CheckImageAndPushImage(coverUrl[0]) #处理图片
		data = data.replace(coverUrl[0],DarenCoverUrl) #替换图片
	except Exception, e:
		print e
		return False

	data = urllib.urlencode({"draft":data})
	req = urllib2.Request("http://we.taobao.com/action.do?api=primus_msg_do_publish_feed&subApi=publish_item&_input_charset=utf-8&_tb_token_="+str(tb_token)+"&timestamp="+timestamp,data)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36')
	req.add_header('Referer', 'http://we.taobao.com/daren/itemPublish.htm?spm=a21a0.7476711.0.0.oPNGDO')
	req.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
	req.add_header('Origin', 'http://we.taobao.com')
	req.add_header('X-Requested-With', 'XMLHttpRequest')
	req.add_header('Accept-Encoding', 'gzip, deflate')
	req.add_header('Cookie', cookies)
	resp = urllib2.urlopen(req)
	try:
		if resp.info().get('Content-Encoding') == 'gzip':
			buf = StringIO( resp.read())
			f = gzip.GzipFile(fileobj=buf)
			data = f.read()
		else:
			data = resp.read()
	except Exception, e:
		print e
	try:
		s = json.loads(data)
		res = s['success']
		setStatus(id,0)
	except Exception, e:
		res = False
	return res

#bill
def BillProduct(dataJson):
	tb_token = redaTxt("cache_tb_token.txt")
	cookies  = redaTxt("cache_cookies.txt")
	if dataJson == "":
		data     = redaTxt("cache_data_2.txt")
	else:
		data = urllib.unquote(dataJson)
		data = data.replace('"id":0,','')
	timestamp = timestamp_now()
	url       = "http://we.taobao.com/action.do?api=primus_msg_do_publish_feed&subApi=publish_daren_album2&_input_charset=utf-8&_tb_token_="+tb_token+"&timestamp=" + timestamp
	data      = re.sub('"_tb_token_":"(.*)"', '"_tb_token_":"'+str(tb_token)+'"',data) #正则替换token
	coverUrl  = re.findall(r'coverUrl":"(.*)","content"',data,re.S) #正则提取coverUrl

	r1 = re.compile('"id":"(.+?)"')
	id = re.findall(r1, data)[0]
	data = data.replace('"id":"'+str(id)+'",',"")

	try:
		DarenCoverUrl = DarenImage.CheckImageAndPushImage(coverUrl[0]) #处理图片
		data = data.replace(coverUrl[0],DarenCoverUrl) #替换图片
	except Exception, e:
		return False

	#替换其他图片
	data = data.replace(".JPG",".jpg")
	r1 = re.compile("(http://.+?\.jpg)")
	imgArr = re.findall(r1, data)
	i = 1
	print "total "+str(len(imgArr))+" images"
	for v in imgArr:
		print "now run No."+str(i)+" images"
		img = DarenImage.CheckImageAndPushImage(v) #处理图片
		data = data.replace(v,img)
		i = i + 1

	data = urllib.urlencode({"draft":data})
	req = urllib2.Request(url,data)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36')
	req.add_header('Referer', 'http://we.taobao.com/daren/newAlbumFeed1.htm')
	req.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
	req.add_header('Origin', 'http://we.taobao.com')
	req.add_header('X-Requested-With', 'XMLHttpRequest')
	req.add_header('Accept-Encoding', 'gzip, deflate')
	req.add_header('Cookie', cookies)
	resp = urllib2.urlopen(req)
	try:
		if resp.info().get('Content-Encoding') == 'gzip':
			buf = StringIO( resp.read())
			f = gzip.GzipFile(fileobj=buf)
			data = f.read()
		else:
			data = resp.read()
	except Exception, e:
		print e
	try:
		s = json.loads(data)
		res = s['success']
		setStatus(id,1)
	except Exception, e:
		res = False
		print data
	return res

#bill
def NoteProduct():
	tb_token = redaTxt("cache_tb_token.txt")
	cookies  = redaTxt("cache_cookies.txt")
	data     = redaTxt("cache_data_3.txt")

	timestamp = timestamp_now()
	url       = "http://we.taobao.com/action.do?api=primus_msg_do_publish_rtf_feed&subApi=publish_daren&_input_charset=utf-8&_tb_token_="+tb_token+"&timestamp=" + timestamp
	data      = re.sub('"_tb_token_":"(.*)"', '"_tb_token_":"'+str(tb_token)+'"',data) #正则替换token
	data = urllib.urlencode({"draft":data})
	req = urllib2.Request(url,data)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36')
	req.add_header('Referer', 'http://we.taobao.com/daren/newAlbumFeed1.htm')
	req.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
	req.add_header('Origin', 'http://we.taobao.com')
	req.add_header('X-Requested-With', 'XMLHttpRequest')
	req.add_header('Accept-Encoding', 'gzip, deflate')
	req.add_header('Cookie', cookies)
	resp = urllib2.urlopen(req)
	try:
		if resp.info().get('Content-Encoding') == 'gzip':
			buf = StringIO( resp.read())
			f = gzip.GzipFile(fileobj=buf)
			data = f.read()
		else:
			data = f.read()
	except Exception, e:
		print error
	try:
		s = json.loads(data)
		res = s['success']
	except Exception, e:
		res = False
	return res

def setStatus(id="",type="0"):
	url      = "http://grapp.t.ou5.cn:83/index/inlet/proving/signtaobao/type/"+str(type)+"/id/"+str(id)
	response = urllib2.urlopen(url) 
	html = response.read()
	try:
		s = json.loads(html)
		res = s['status']
	except Exception, e:
		res = False
	return res


app,browser,MessageBox=None,None,None
 
class BrowserScreen(QWebView): 
    '''主窗口'''
    def __init__(self): 
        QWebView.__init__(self) 
        self.resize(1200, 768) 
        self.setHtml(open('view/index.html').read().decode('utf-8'))
        #self.load(QUrl(r'http://www.taobao.com'))
        self.show() 
     
    def showMessage(self, msg): 
        return "1231231"
 
 
class PythonJS(QObject): 
    '''供js调用'''
    __pyqtSignals__ = ( "contentChanged(const QString &)" ) 

    @pyqtSignature("")
    def close(self):
        sys.exit()
     
    @pyqtSignature("") 
    def openMap(self): 
        #browser.setHtml(open('test1.html').read().decode('utf-8'))   
        browser.load(QUrl(r'http://www.atool.org/useragent.php')) 

    @pyqtSignature("QString", result="QString")
    def SingleProduct(self, data = "*"):
    	try:
    		print u"开始执行单品模拟插入"
    		print data
    		data = unicode(data.toUtf8(), 'utf-8', 'ignore').encode("utf-8")
    		res = SingleProduct(data)
    		if res == True:
    			print u"插入成功"
    			return outTxt(1)
    		else:
    			Login()
    			res = SingleProduct(data)
    			if res==True:
					print u"插入成功"
					return outTxt(1)

    	except Exception, e:
    		print Exception,e
    		print u'程序出错本次执行结束!!!!!'
    	print u"插入失败"
    	return outTxt(0)

    @pyqtSignature("QString", result="QString")
    def Bill(self, data = "*"):
    	try:
    		print u"开始执行清单模拟插入"
    		print data
    		data = unicode(data.toUtf8(), 'utf-8', 'ignore').encode("utf-8")    		
    		res = BillProduct(data)
    		if res == True:
    			print u"插入成功"
    			return outTxt(1)
    		else:
    			Login()
    			res = BillProduct(data)
    			if res==True:
					print u"插入成功"
					return outTxt(1)

    	except Exception, e:
    		print e
    		print u'程序出错本次执行结束!!!!!'
    	print u"插入失败"	
    	return outTxt(0)

    @pyqtSignature("",str)
    def Note(self):
    	try:
    		print u"开始执行帖子模拟插入"
    		res = NoteProduct()
    		if res == True:
    			print u"插入成功"
    			return u"插入成功"
    		else:
    			Login()
    			res = NoteProduct()
    			if res==True:
					print u"插入成功"
					return u"插入成功"

    	except Exception, e:
    		print e
    		print u'程序出错本次执行结束!!!!!'
    	return u"插入失败"

if __name__== '__main__' :
    app = QApplication(sys.argv)
    browser = BrowserScreen()
    #供js调用的python对象
    pjs = PythonJS()
    #绑定通信对象
    browser.page().mainFrame().addToJavaScriptWindowObject( "python" , pjs)
    #QObject.connect(pjs , SIGNAL( "contentChanged(const QString &)" ), browser.showMessage)
    sys.exit(app.exec_())